import { STORAGE_TOKEN_KEY } from '@/store/mutation-type';

/**
 * token 操作封装
 */
export const TOKEN_STORE_NAME = STORAGE_TOKEN_KEY;

// 登录状态
export function isLogin(): boolean {
  return !!getToken();
}

/**
 * 获取缓存的 token
 */
export function getToken(): string | null {
  const token = localStorage.getItem(TOKEN_STORE_NAME);
  if (!token) {
    return sessionStorage.getItem(TOKEN_STORE_NAME);
  }
  return token;
}

/**
 * 缓存 token
 * @param token token
 * @param remember 是否永久存储
 */
export function setToken(token: string, remember = false): void {
  // removeToken()
  if (token) {
    if (remember) {
      localStorage.setItem(TOKEN_STORE_NAME, token);
    } else {
      sessionStorage.setItem(TOKEN_STORE_NAME, token);
    }
  }
}

/**
 * 移除 token
 */
export function clearToken(): void {
  localStorage.removeItem(TOKEN_STORE_NAME);
  sessionStorage.removeItem(TOKEN_STORE_NAME);
}
